package com.stars.easyms.alarm.service;

import com.stars.easyms.alarm.client.EasyMsAlarmClient;
import com.stars.easyms.alarm.client.EasyMsAlarmClientFactory;
import com.stars.easyms.alarm.message.EasyMsAlarmMessage;
import com.stars.easyms.base.asynchronous.BaseAsynchronousTask;
import com.stars.easyms.base.constant.EasyMsCommonConstants;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * <p>className: EasyMsAsynAlarmService</p>
 * <p>description: EasyMs实现的异步告警服务类</p>
 *
 * @author guoguifang
 * @version 1.6.3
 * @date 2020/9/19 10:45 上午
 */
public class EasyMsAsynAlarmService extends BaseAsynchronousTask<EasyMsAlarmMessage> {

    @Override
    protected boolean execute(EasyMsAlarmMessage alarmMessage) {
        // 获取到告警客户端ID，如果没有指定则使用默认的
        String clientId = StringUtils.isBlank(alarmMessage.getClientId()) ? EasyMsCommonConstants.DEFAULT : alarmMessage.getClientId().trim();
        final List<EasyMsAlarmClient> alarmClientList = EasyMsAlarmClientFactory.getAlarmClientList(clientId);
        if (!alarmClientList.isEmpty()) {
            for (EasyMsAlarmClient alarmClient : alarmClientList) {
                try {
                    alarmClient.sendAlarmMessage(alarmMessage);
                } catch (Exception e) {
                    logger.error("Easy-ms {} alarm client '{}' send message fail!",
                            alarmClient.getAlarmChannel().getChannelType(), clientId, e);
                }
            }
        } else {
            logger.error("Can't find Easy-ms alarm client '{}'!", clientId);
        }
        return true;
    }
}
